package com.wfm.leetcode.editor.cn;

import com.wfm.common.TreeNode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *      3
 *     9  20
 *       15  7
 * 输出
 *  【
 *      [3],
 *      [20,9],
 *      [15,7]
 *   】
 */
public class P剑指Offer32III从上到下打印二叉树III{
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if(root==null){
            return res;
        }
        queue.offer(root);
        int odd = 1;
        while (!queue.isEmpty()){
            Deque<Integer> tmp = new LinkedList<>();
            int curSize = queue.size();
            if(odd%2==0){
                for (int i = 0; i < curSize; i++) {
                    TreeNode poll = queue.poll();
                    tmp.addFirst(poll.val);
                    if(poll.left!=null) queue.offer(poll.left);
                    if(poll.right!=null) queue.offer(poll.right);
                }
            }else{
                for (int i = 0; i < curSize; i++) {
                    TreeNode poll = queue.poll();
                    tmp.addLast(poll.val);
                    if(poll.left!=null) queue.offer(poll.left);
                    if(poll.right!=null) queue.offer(poll.right);
                }
            }
            res.add(new LinkedList<>(tmp));
            odd++;

        }
        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) { 
        Solution solution = new P剑指Offer32III从上到下打印二叉树III().new Solution();
    }
}